<?php
/**
 * Created by PhpStorm.
 * User: Tsang
 * Date: 2017/9/24 16:20
 *
 */

namespace app\api\model;


use think\Model;

class Member extends Model
{

    /**
     * 获取用户信息
     * @param $original
     * @return array
     */
    public function getUser($original)
    {
        $openid = $original['original']['wx_openid'];
        $userData = $this->getByOpenID($openid);

        if (empty($userData)){
            $resultData = $this->createUser($original['original']);
        }else{
            $resultData = $this->updateUser($userData['id'],$original['original']);
        }

        $resultData['user'] = $userData;
        return $resultData;
    }

    /**
     * 微信openid对应的用户是否存在
     * 存在返回uid，不存在返回0
     */
    public static function getByOpenID($openid)
    {
        $user = Member::where('wx_openid', '=', $openid)->find();
        if(empty($user)){
            return [];
        }
        $member = $user->toArray();
        unset($member['passwd']);
        return $member;
    }

    /**
     * 根据id获取用户信息
     * @param $uid
     * @return array
     *
     */
    public static function getByUID($uid)
    {
        $user = Member::where('id', '=', $uid)
            ->find();
        if(empty($user)){
            return [];
        }
        $member = $user->toArray();
        unset($member['passwd']);
        return $member;
    }

    /**
     * 创建用户
     * @param $original
     * @return mixed
     */
    private function createUser($original)
    {
        $original['create_time'] = time();
        $user = Member::create($this->dataFormat($original));
        if ($user->id == 0)
            return array('message'=>'授权登录失败','type'=>'create');
    }

    /**
     * @param $original
     * @return mixed
     */
    private function dataFormat($original)
    {
        $data = [];
        foreach ($original as $k=>$v){
            if($v != "") $data[$k] = $v;
        }
        return $data;
    }

    /**
     * 更新用户
     * @param $root
     * @param $code
     * @return \think\response\Json
     */
    public function updateUser($uid,$original)
    {
        $affectedRows =  db('member')->where('id',$uid)
            ->update($this->dataFormat($original));
        if ($affectedRows == 0)
            return array('message'=>'更新用户信息失败','type'=>'update');
    }

}